# coding:utf-8
# 战斗管理器

import time, cProfile
import glog, glb
import account_mgr, role_mgr, battlearray_mgr, card_mgr, mission_mgr
from battle_calc import BattleCalc
from battle_unit import BattleUnit, BattleMatrix, MissionBattleMatrix
from glb import BATTLE_SIDE_A, BATTLE_SIDE_B, BATTLE_FRAME_PER_SECOND
import DATA_pet



def init ():
	pass


# 开始战斗 闯关
def start_battle_pve (params, account, role):
	glog.log('start_battle_pve ' + repr(params))
	mission_id = params[0]

	# 玩家
	ma = get_player_matrix(BATTLE_SIDE_A, role)
	# 关卡
	mb = get_mission_matrix(BATTLE_SIDE_B, mission_id)

	if ma is None or mb is None:
		glog.debug('ma:' + repr(ma))
		glog.debug('mb:' + repr(mb))
		glog.error('battle_mgr>start_battle_pve: get Matrix Error')
		return glb.return_err('battle_mgr>start_battle_pve: get Matrix Error')

	battle_data = run_battle(ma, mb)

	# 战斗效率分析
	cProfile.runctx('run_battle(ma, mb)', globals(), locals(), 'log_file.pyprof')

	# 通知mission_mgr
	mission_mgr.on_battle_pve(role, mission_id, battle_data['result']['battle_result'])
	return glb.return_ok(battle_data)	


# 取得玩家BattleMatrix
def get_player_matrix (side, role):
	ba = battlearray_mgr.get(role.id)
	if ba is None:
		glog.error('battle_mgr>get_player_matrix:battlearray is None, role:%s' % role.id)
		return

	units = []
	for pos, card_id in ba.iteritems():
		if card_id is None: continue

		x, y = _pos2xy(pos)
		card = card_mgr.get(role.id, card_id)
		if card is None:
			glog.error('battle_mgr>get_player_matrix:can NOT get card, role:%s card:%s' % (role.id, card_id))
			return

		is_player = True
		skill = DATA_pet.data[card.type]['skill']
		u = BattleUnit(is_player, side, x, y, card.type, 100, 50, 200, 100, skill)
		# 移动速度
		u.move_speed_frames = DATA_pet.data[card.type]['move_speed'] / (1000 / BATTLE_FRAME_PER_SECOND)
		units.append(u)

	if len(units) == 0:
			glog.error('battle_mgr>get_player_matrix:len(units)==0')
			return

	m = BattleMatrix(role, units)
	return m


# 把1~6转换成坐标
def _pos2xy (pos):
	if pos <= 3:
		x = 0
		y = 3 - pos
	else:
		x = 2
		y = 3 - (pos - 3)
	return x, y


# 取得关卡BattleMatrix
def get_mission_matrix (side, mission_id):
	m = MissionBattleMatrix(side, mission_mgr.DATA_mission_enemy[mission_id])
	m.next_wave()
	return m


# 玩家对玩家
def start_battle_pvp ():
	pass


def run_battle (ma, mb):
	t1 = time.time()
	calc = BattleCalc(ma, mb)
	calc.run()
	t2 = time.time()
	glog.info('run_battle time:'+str(t2-t1))
	#print "battle log:", calc.log
	return calc.log


def test ():
	u1 = BattleUnit(BATTLE_SIDE_A, 0, 2, 1, 100, 50, 200, 100)
	u2 = BattleUnit(BATTLE_SIDE_A, 1, 2, 1, 100, 50, 200, 100)
	u3 = BattleUnit(BATTLE_SIDE_B, 7, 2, 1, 100, 50, 200, 100)
	u4 = BattleUnit(BATTLE_SIDE_B, 8, 2, 1, 100, 50, 200, 100)

	ma = BattleMatrix(None, [u1, u2])
	mb = BattleMatrix(None, [u3, u4])
	log_data = run_battle(ma, mb)
	return glb.return_ok(log_data)

